package csycompany.excel;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.VerticalAlignment;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import me.zhouzhuo.zzexcelcreator.ZzExcelCreator;
import me.zhouzhuo.zzexcelcreator.ZzFormatCreator;

public class MainActivity extends AppCompatActivity {

    private static final String PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/CSY/";
    private static ZzExcelCreator creator;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        if (Build.VERSION.SDK_INT >= 23) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0x01);
            } else {
                createExcel();
            }
        } else {
            createExcel();
        }


        insertExcel("0", "0", "idshi 1");
        insertExcel("1", "0", "status 0");


        insertExcel("0", "1", "idshi 2");
        insertExcel("1", "1", "status 0");


        insertExcel("0", "2", "idshi 3");
        insertExcel("1", "2", "status 1");

        Workbook workbook = null;
        try {
            workbook = Workbook.getWorkbook(new File(PATH + "失败列表" + ".xls"));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (BiffException e) {
            e.printStackTrace();
        }
        //获取第一个工作表的对象
        Sheet sheet = workbook.getSheet(0);
        int a = sheet.getRows();
        if (a == 3) {
            insertExcel("0", a + "", "idshi 4");
            insertExcel("1", a + "", "status 0");
        }


//        File file;
//        File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/csycompany.excel/downloadimg/" + "失败电话号码1" + ".xls");
//        file = new File(String.valueOf(dir));
//        if (!dir.exists()) {
//            dir.mkdirs();
//            WritableWorkbook wwb;
//            OutputStream os = null;
//            try {
//                os = new FileOutputStream(file);
//                wwb = Workbook.createWorkbook(os);
//                WritableSheet sheet = wwb.createSheet("失败列表", 0);
//                String[] title = {"id", "状态值"};
//                Label label;
//                for (int i = 0; i < title.length; i++) {
//                    // Label(x,y,z) 代表单元格的第x+1列，第y+1行, 内容z
//                    // 在Label对象的子对象中指明单元格的位置和内容
//                    label = new Label(i, 0, title[i], getHeader());
//                    // 将定义好的单元格添加到工作表中
//                    sheet.addCell(label);
//                }
//                for (int i = 0; i < 3; i++) {
//                    Label orderNum = new Label(0, i + 1, "id 是" + i);
//                    Label restaurant = new Label(1, i + 1, "状态" + i);
//                    sheet.addCell(orderNum);
//                    sheet.addCell(restaurant);
//                }
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            } catch (IOException e) {
//                e.printStackTrace();
//            } catch (RowsExceededException e) {
//                e.printStackTrace();
//            } catch (WriteException e) {
//                e.printStackTrace();
//            }
//        } else {
//
//        }


    }

    private void insertExcel(final String col, final String row, final String str) {
        new AsyncTask<String, Void, Integer>() {

            @Override
            protected Integer doInBackground(String... params) {
                try {
                    WritableCellFormat format = ZzFormatCreator
                            .getInstance()
                            .createCellFont(WritableFont.ARIAL)
                            .setAlignment(Alignment.CENTRE, VerticalAlignment.CENTRE)
                            .setFontSize(14)
                            .setFontColor(Colour.DARK_GREEN)
                            .getCellFormat();
                    ZzExcelCreator
                            .getInstance()
                            .openExcel(new File(PATH + "失败列表" + ".xls"))
                            .openSheet(0)
                            .setColumnWidth(Integer.parseInt(col), 25)
                            .setRowHeight(Integer.parseInt(row), 400)
                            .fillContent(Integer.parseInt(col), Integer.parseInt(row), str, format)
                            .close();
                    return 1;
                } catch (IOException | WriteException | BiffException e) {
                    e.printStackTrace();
                    return 0;
                }
            }

            @Override
            protected void onPostExecute(Integer aVoid) {
                super.onPostExecute(aVoid);
                if (aVoid == 1) {
                    Toast.makeText(MainActivity.this, "插入成功！", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "插入失败！", Toast.LENGTH_SHORT).show();
                }
            }
        }.execute(col, row, str);
    }


    public static WritableCellFormat getHeader() {
        WritableFont font = new WritableFont(WritableFont.TIMES, 10,
                WritableFont.BOLD);// 定义字体
        try {
            font.setColour(Colour.BLUE);// 蓝色字体
        } catch (WriteException e1) {
            e1.printStackTrace();
        }
        WritableCellFormat format = new WritableCellFormat(font);
        try {
            format.setAlignment(jxl.format.Alignment.CENTRE);// 左右居中
            format.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);// 上下居中
            format.setBorder(Border.ALL, BorderLineStyle.THIN,
                    Colour.BLACK);// 黑色边框
            format.setBackground(Colour.YELLOW);// 黄色背景
        } catch (WriteException e) {
            e.printStackTrace();
        }
        return format;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 0x01:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    createExcel();
                }
                break;
        }
    }

    private void createExcel() {
        new AsyncTask<String, Void, Integer>() {

            @Override
            protected Integer doInBackground(String... params) {
                try {
                    ZzExcelCreator
                            .getInstance()
                            .createExcel(PATH, params[0])
                            .createSheet(params[1])
                            .close();
                    return 1;
                } catch (IOException | WriteException e) {
                    e.printStackTrace();
                    return 0;
                }
            }

            @Override
            protected void onPostExecute(Integer aVoid) {
                super.onPostExecute(aVoid);
                if (aVoid == 1) {
                    Toast.makeText(MainActivity.this, "表格创建成功！请到" + PATH + "路径下查看~", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "表格创建失败！", Toast.LENGTH_SHORT).show();
                }
            }
        }.execute("失败列表", "无");
    }


}
